/** 
 * Project Name:kaka 
 * File Name:WechatUserInfoServiceImpl.java 
 * Package Name:com.luoran.kaka.service.impl 
 * Date:2018年12月14日下午12:39:31 
 * Copyright (c) 2018, Luoran, Inc. All Rights Reserved.
 * 
 */
package com.luoran.kaka.service.impl;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.luoran.kaka.api.wechat.model.WechatUserInfo;
import com.luoran.kaka.dao.IWechatUserInfoDao;
import com.luoran.kaka.service.IWechatUserInfoService;

/** 
 * @author ghl 
 * @since JDK 1.8
 * ClassName: WechatUserInfoServiceImpl
 * date: 2018年12月14日 下午12:39:31
 *	
 */
@Service
public class WechatUserInfoServiceImpl implements IWechatUserInfoService {

	public static final Logger log = LoggerFactory.getLogger(WechatUserInfoServiceImpl.class);

	@Autowired
	private IWechatUserInfoDao wechatUserInfoDao;

	/** 
	 * @see com.luoran.kaka.service.IWechatUserInfoService#SyncWechatUserInfo(com.luoran.kaka.api.wechat.model.WechatUserInfo) 
	 * @param userInfo
	 * @author ghl 2018年12月14日下午12:47:07
	 * SyncWechatUserInfo:同步微信用户信息
	 */
	@Transactional
	@Override
	public void SyncWechatUserInfo(WechatUserInfo entity) {

		try {
			String openid = entity.getOpenId();
			WechatUserInfo userInfo = wechatUserInfoDao.getWechatUserInfoByOpenId(openid);
			// 如果没查到,就保存
			if (null == userInfo) {
				log.info("检测到当前用户为新用户,保存用户基本信息");
				entity.setCreatetime(new Date());
				wechatUserInfoDao.insertTemplate(entity);
			} else {
				// 如果查到了就做更新操作.
				log.info("检测到当前用户为老用户,更新用户信息");
				userInfo.setNickName(entity.getNickName());// 昵称
				userInfo.setAvatarUrl(entity.getAvatarUrl());// 头像
				userInfo.setGender(entity.getGender());// 性别
				userInfo.setLanguage(entity.getLanguage());
				userInfo.setCountry(entity.getCountry());// 国家
				userInfo.setProvince(entity.getProvince());// 省
				userInfo.setCity(entity.getCity());// 市
				userInfo.setSessionKey(entity.getSessionKey());
				userInfo.setUnionId(entity.getUnionId());//
				userInfo.setLastupdatetime(new Date());
				wechatUserInfoDao.updateTemplateById(userInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("同步微信用户基本信息失败,详情查看服务器日志.{}", e.getMessage());
			throw new RuntimeException();
		}
	}


}
